package com.soul.doc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.soul.common.exception.BaseException;
import com.soul.common.utils.ListUtil;
import com.soul.doc.bean.dto.CollectionDto;
import com.soul.doc.bean.po.LoveSongListPo;
import com.soul.doc.mapper.LoveSongListMapper;
import com.soul.doc.service.LoveSongListService;
import com.soul.common.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户收藏歌单 服务实现类
 * </p>
 *
 * @author sws
 * @since 2023-12-06 16:32:35
 */
@Service
public class LoveSongListServiceImpl extends BaseService<LoveSongListMapper, LoveSongListPo> implements LoveSongListService {

    @Override
    public boolean addLoveSongList(CollectionDto collectionDto){
        if (!StpUtil.isLogin()){
            throw new BaseException("未登录");
        }
        long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 100L;
        List<LoveSongListPo> list = this.getLambadaQueryWrapper().eq(LoveSongListPo::getUserId, userId).list();
        List<Long> songListIds = ListUtil.toValueList(list, LoveSongListPo::getSongListId);
        if (ObjectUtil.isNotEmpty(songListIds) && songListIds.contains(collectionDto.getSongListId())){
            if (ObjectUtil.equals(collectionDto.getType(),"remove")){
                // 取消收藏
                List<Long> longs = this.getLambadaQueryWrapper()
                        .eq(LoveSongListPo::getUserId, userId)
                        .eq(LoveSongListPo::getSongListId, collectionDto.getSongListId())
                        .listField(LoveSongListPo::getId);
                this.removeByIds(longs);
                return true;
            }
            return false;
        }
        LoveSongListPo loveSongListPo = new LoveSongListPo();
        loveSongListPo.setSongListId(collectionDto.getSongListId())
                .setUserId(userId);
        Long maxSort = this.getMaxSort(LoveSongListPo::getUserId, userId);
        loveSongListPo.setSort(maxSort);
        this.save(loveSongListPo);
        return true;
    }

    @Override
    public List<LoveSongListPo> getLoveSongList(){
        if (!StpUtil.isLogin()){
            throw new BaseException("未登录");
        }
        long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 100L;
        return this.getLambadaQueryWrapper().eq(LoveSongListPo::getUserId, userId).list();
    }

    @Override
    public boolean isSongListLove(Long songListId){
        if (StpUtil.isLogin()){
            long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 100L;
            return this.getLambadaQueryWrapper().eq(LoveSongListPo::getSongListId,songListId)
                    .eq(LoveSongListPo::getUserId, userId).count() > 0;
        }
        return false;
    }
}
